import React, {Component} from 'react';
import {
  StyleSheet,
  Text,
  View,
  Image,
  ImageBackground,
  Dimensions,
  findNodeHandle,
  TouchableOpacity,
  SafeAreaView,
  StatusBar,
  ActivityIndicator,
} from 'react-native';
import Video from 'react-native-video';
import Entypo from 'react-native-vector-icons/Entypo';
import Colors from '../../util/Colors';
import MusicHeader from './MusicHeader';

import {BlurView} from '@react-native-community/blur';
import RotateAnimator from './RotateAnimator';
import SeekBar from './SeekBar';
import LyricComonent from './LyricComponent';
import StringUtil from '../../util/StringUtil';
export default class MusicPlayer extends Component {
  constructor(props) {
    super(props);
    // let song = this.props.navigation.getParam('song'); // 从导航中取数据


    this.state = {
      viewRef: null,
      song: props.currentMusic,
      isPlaying: props.play,
      position: props.currentTime,
      duration: props.duration, // 给个值，防止刚开始进度条就是满的
      hasCover:  false,
      showLrc:false,
      processStartX:0,
      isPressBar:false,
      loading:true
    };

  }

  static getDerivedStateFromProps(props, state){

    let result = {};
    if(props.play !== state.isPlaying){
      result.isPlaying = props.play;
    }

    if(props.currentTime !== state.position){
      //console.log("差值："+ (props.currentTime - state.position < 1000 && props.currentTime - state.position > 0 ));

      if(!props.seeked || (props.currentTime - state.position < 1000 && props.currentTime - state.position > 0 ) || (props.currentTime - state.position > -1000 && props.currentTime - state.position < 0)){

        //console.log("自动更新");
        result.position = props.currentTime;
      }else if(props.currentTime <= 100){
        //console.log("自动重置");
        result.position = props.currentTime;
      }

    }

    if(props.duration !== state.duration){
      result.duration = props.duration;
    }

    if(props.currentMusic !== state.song){
      result.song = props.currentMusic;
    }
    return result;
  }

  componentDidMount(){
    StatusBar.setBarStyle('light-content');
    this.props.setPlayControlBottom(false);
  }

  getImageSource() {
    let source;
    if(this.state.song.img){
      source = {uri:this.state.song.img}
    }else
      source = require('../../images/music_cover.jpg');


    return source;
  }

  imageLoaded() {
    //console.log('imageLoaded ' + this.state.song.name);
    setTimeout(() => {
      this.setState({
        viewRef: findNodeHandle(this.backgroundImage),
        loading:false
      });
    }, 200);
  }

  loadSongDetail() {
    //console.log('loadSong');
  }

  _renderBackground() {
    if (this.state.song.img) {
      return (
        <View style={styles.absolute}>
          <Image
            ref={img => {
              this.backgroundImage = img;
            }}
            source={this.getImageSource()}
            style={this.state.viewRef == null ? styles.hidden : styles.absolute}
            onLoadEnd={this.imageLoaded.bind(this)}
          />
          {this.state.viewRef != null && (<BlurView
            style={styles.absolute}
            viewRef={this.state.viewRef}
            blurType="dark"
            blurAmount={20}
          />)}

        </View>
      );
    }
  }

  _renderLoading() {
    if (this.state.loading) {
      return (
        <View style={[styles.absolute, {justifyContent: 'center'}]}>
          <ActivityIndicator
            size={46}
            color={Colors.colorLight}
            animating={true}
          />
        </View>
      );
    }
  }

  _renderProgressBar() {
    return (
      <View style={styles.progressBar}
            onLayout={(e) => {
          this.setState({processStartX:e.nativeEvent.layout.x})
      }}>
        <Text style={styles.textTime}>
          {StringUtil.formatTime(this.state.position)}
        </Text>

        <SeekBar
          style={{flex: 1, marginLeft: 20, marginRight: 20}}
          progressHeight={2}
          progress={this.state.position}
          processStartX={this.state.processStartX}
          min={0}
          max={this.state.duration}
          onStartTouch={() => {
            this.props.setIsPressed(true);
            this.setState({isPressBar:true})
          }}
          onProgressChanged={value => {
            //console.log('onProgressChanged:' + value);

          }}
          onStopTouch={position => {
            this.props.setIsPressed(false);
            this.props.setCurrentTime(position);
            this.props.setSeeked(false);
            this.setState({isPressBar:false})
            this.props.player.current.seek(position / 1000);
          }}
        />

        <Text style={styles.textTime}>
          {StringUtil.formatTime(this.state.duration)}
        </Text>
      </View>
    );
  }
  next = () => {

    if(this.props.musicList.length>0) {
      let index = this.props.musicList.findIndex((r) => {
        return r.id === this.props.currentMusic.id && r.name === this.props.currentMusic.name;
      });
      if(index + 1 <this.props.musicList.length)
        this.props.setCurrentMusic(this.props.musicList[index+1])
      else
        this.props.setCurrentMusic(this.props.musicList[0])
    }
  }
  before = () => {
    if(this.props.musicList.length>0) {
      let index = this.props.musicList.findIndex((r) => {
        return r.id === this.props.currentMusic.id && r.name === this.props.currentMusic.name;
      });
      if(index > 0)
        this.props.setCurrentMusic(this.props.musicList[index-1])
      else
        this.props.setCurrentMusic(this.props.musicList[this.props.musicList.length - 1])
    }
  }
  _renderControllerBar() {
    let iconColor = '#ffffffdd';
    //console.log('isplaying'+this.state.isPlaying);
    return (
      <View style={styles.controllerBar}>
        <Entypo
          name={'controller-jump-to-start'}
          size={40}
          color={iconColor}
          onPress={this.before}
        />
        <Entypo
          style={{marginLeft: 20, marginRight: 20}}
          name={this.state.isPlaying ? 'controller-paus' : 'controller-play'}
          size={60}
          color={iconColor}
          onPress={() => {

            isPlaying: this.props.setPlay(!this.state.isPlaying)

          }}
        />
        <Entypo
          name={'controller-next'}
          size={40}
          color={iconColor}
          onPress={this.next}
        />
      </View>
    );
  }
  add = (v) => {
      this.props.setToAdd(true);
      this.props.setToAddValue(v);
  }
  render() {
    let song = this.state.song;
    return (
      <View style={styles.page} >
        <StatusBar
          barStyle="light-content"
          backgroundColor="transparent"
          translucent={true}
        />
        {this._renderBackground()}

        <SafeAreaView style={styles.content} forceInset={{top: 'always'}}
        >
          <MusicHeader
            style={{marginBottom: 26}}
            song={song}
            add={this.add}
            onPress={() => this.props.navigation.pop()}
          />
          <View style={styles.imgAndLrc}>
            <TouchableOpacity
              onPress={() => {
                this.setState({showLrc:!this.state.showLrc})
              }}>
              {this.state.showLrc?


                  <LyricComonent loaded={() => this.setState({loading:false})} setCurrentMusic={this.props.setCurrentMusic} song={this.state.song} position={this.state.position} />

                :
                  <View>
                    <View style={{height:planeHeight}}>

                    </View>
                    <RotateAnimator  duration={24000} running={this.state.isPlaying}>
                      <Image
                        roundAsCircle={true}
                        source={this.getImageSource()}
                        style={styles.coverImage}

                      />
                      {this._renderLoading()}
                    </RotateAnimator>

                  </View>
              }
            </TouchableOpacity>
          </View>

            {this._renderProgressBar()}

            {this._renderControllerBar()}

        </SafeAreaView>
      </View>
    );
  }

  componentWillUnmount() {
    this.props.setPlayControlBottom(true);
  }


}

const screen = Dimensions.get('window');
const imageSize = 240;
const itemHeight = 80; // 如果可以确定高度，免去了渲染计算高度
const visibleItemSize = screen.height < 700 ? 5 : 7;
const planeHeight = (screen.height - imageSize)/4;
const styles = StyleSheet.create({
  page: {
    flex: 1,
    backgroundColor: '#555555',
    flexDirection: 'column',
    alignItems: 'center', // 子元素沿主轴的对齐方式

  },
  content: {
    flex: 1,
    flexDirection: 'column',
    alignItems: 'center', // 子元素沿主轴的对齐方式
    marginTop: Platform.OS === 'ios' ? 0 : StatusBar.currentHeight,
  },
  imgAndLrc: {
    flex:4
  },
  controller:{
    flex:1
  },
  coverImage: {
    width: imageSize,
    height: imageSize,
    borderRadius: imageSize / 2,
  },
  absolute: {
    position: 'absolute',
    top: 0,
    left: 0,
    bottom: 0,
    right: 0,
  },
  hidden: {
    width: 0,
    height: 0,
  },
  controllerBar: {
    flexDirection: 'row',
    alignItems: 'center', // 子元素沿主轴的对齐方式
    //marginTop: 16,
    marginBottom: 20,
  },
  progressBar: {
    flexDirection: 'row',
    alignItems: 'center', // 子元素沿主轴的对齐方式
    marginLeft: 20,
    marginRight: 20,
    marginBottom:8
  },
  textTime: {
    fontSize: 12,
    color: '#ffffff',
  },
});
